package com.gitee.wsl.io

import com.gitee.wsl.ext.array.hashSHA256toString
import com.gitee.wsl.ext.array.hashSHA512toString
import com.gitee.wsl.ext.array.toByteString
import com.gitee.wsl.ext.string.decodeHexToByteArray
import kotlinx.io.Buffer
import kotlinx.io.bytestring.ByteString
import kotlinx.io.bytestring.encodeToByteString
import kotlinx.io.bytestring.toHexString
import kotlin.math.min

fun String.toByteString() = this.encodeToByteString()

val ByteString.isProbablyPlainText: Boolean
    get() {
        val byteCount = min(size, MAX_PREFIX_SIZE.toInt())
        return Buffer().apply { write(toByteArray(), startIndex = 0, byteCount)}.isProbablyPlainText
    }

/*
fun ByteString.fromGzip(): ByteString = Buffer().use { buf ->
    buf.write(this)
    (buf as Source).gzip().buffer().use { it.readByteString() }
}

fun ByteString.toGzip(): ByteString = Buffer().use { buf ->
    (buf as Sink).gzip().buffer().use { it.write(this) }
    buf.use { it.readByteString() }
}*/

@OptIn(ExperimentalStdlibApi::class)
fun ByteString.hex() = toHexString()

fun ByteString.sha256() = toByteArray().hashSHA256toString().toByteString()

fun ByteString.sha512() = toByteArray().hashSHA512toString().toByteString()

//fun String.decodeHexToByteString() = decodeHexToByteArray().toByteString()

fun String.decodeHexToByteString() = hexToByteArray().toByteString()